package com.jincp.common.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jinchunping on 2019/2/14.
 */

public class GsonUtil {

    protected static GsonUtil Instance;
    private Gson gson;

    protected GsonUtil() {
        gson = new Gson();
    }

    public static GsonUtil getInstance() {
        if (Instance == null) {
           synchronized (GsonUtil.class){
               if (Instance == null) {
                   Instance = new GsonUtil();
               }
           }
        }
        return Instance;
    }

    public Gson getGson() {
        return gson;
    }

    public <T> T jsonToObject(String json, Class<T> classObj) {
        T result = null;
        try {
            result = gson.fromJson(json, classObj);
        } catch (Exception e) {
            e.printStackTrace();
            MyLogger.e("JsonToObj Error\n" + "Error Msg:" + e.getMessage() + "\nJson = " + json);
        }
        return result;
    }

    public <T> T jsonToObject(String json, Type type) {
        T result = null;
        try {
            result = gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
            MyLogger.e("JsonToObj Error\n" + "Error Msg:" + e.getMessage() + "\nJson = " + json);
        }
        return result;
    }

    public String objectToJson(Object object, Class<?> classObj) {
        String result = "";
        try {
            result = gson.toJson(object, classObj);
        } catch (Exception e) {
            e.printStackTrace();
            MyLogger.e("ObjToJson Error\n" + "Error Msg:" + e.getMessage() + "\nObjName=" + object.getClass().getSimpleName());
        }
        return result;
    }

    public String objectToJson(Object object, Type type) {
        String result = "";
        try {
            result = gson.toJson(object, type);
        } catch (Exception e) {
            e.printStackTrace();
            MyLogger.e("ObjToJson Erro\n" + "Error Msg:" + e.getMessage() + "\nObjName=" + object.getClass().getSimpleName());
        }
        return result;
    }

    public String objectToJson(Object object) {
        String result = "";
        try {
            result = gson.toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
            MyLogger.e("ObjToJson Erro\n" + "Error Msg:" + e.getMessage() + "\nObjName=" + object.getClass().getSimpleName());
        }
        return result;
    }


    public <T> List<T> jsonToList(String jsonString, Class<T> type) {
        ArrayList<T> list = new ArrayList<T>();
        try {
            Type typeToken = new TypeToken<List<T>>() {}.getType();
            list = gson.fromJson(jsonString, typeToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
